package com.xuanyuan.pullup

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.lang.IllegalStateException

/**
 * 基础的权限 Activity
 *
 * @author LUOFAXIN
 */
abstract class BasePermissionsActivity : AppCompatActivity() {

    /**
     * 准备开始申请权限
     */
    protected fun startGetPermissions() {
        beforeGrantedPermissions()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermissions()
        } else {
            grantedAllPermissions()
        }
    }

    abstract fun permissions(): ArrayList<String>?

    /**
     * 授权之前的操作
     */
    abstract fun beforeGrantedPermissions()

    /**
     * 获取所有的权限,进行下一步操作
     */
    abstract fun grantedAllPermissions()

    /**
     * 验证权限的合法性,有些权限要单独验证
     */
    private fun verifyPermissionsLegal() {
        permissions()?.let {
            if (it.contains(Manifest.permission.WRITE_SETTINGS)) {
                throw  IllegalStateException("WRITE_SETTINGS 需要单独申请权限,请调用openWriteSettings()方法")
            }
            if (it.contains(Manifest.permission.CHANGE_NETWORK_STATE) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                throw  IllegalStateException("CHANGE_NETWORK_STATE 在6.0设备中无法被授权")
            }
            if (it.contains(Manifest.permission.READ_LOGS) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                throw  IllegalStateException("READ_LOGS 在Android4.3以后成为了系统级权限")
            }
        }
    }

    /**
     * 检查权限匹配
     */
    private fun checkPermissions() {
        if (permissions() == null) {
            return
        }
        permissions()?.let {
            if (it.size <= 0) {
                return
            } else {
                verifyPermissionsLegal()

                // 第 1 步: 检查是否有相应的权限
                val arr = it.toTypedArray()
                val isAllGranted = checkPermissionAllGranted(arr)
                // 如果这3个权限全都拥有, 则直接执行备份代码
                if (!isAllGranted) {
                    //第 2 步: 请求权限
                    // 一次请求多个权限, 如果其它有权限是已经授予的将会自动忽略掉
                    ActivityCompat.requestPermissions(this, arr, PERMISSION_REQUEST_CODE)
                } else {
                    grantedAllPermissions()
                }
            }
        }


//        String[] arr = new String[]{
//                Manifest.permission.MODIFY_AUDIO_SETTINGS,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.READ_PHONE_STATE,
//                Manifest.permission.ACCESS_NETWORK_STATE,
//                Manifest.permission.ACCESS_COARSE_LOCATION,
//                Manifest.permission.VIBRATE,
//                Manifest.permission.CAMERA
//        };


    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private fun checkPermissionAllGranted(permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false
            }
        }
        return true
    }

    /**
     * 第 3 步: 申请权限结果返回处理
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        var isAllGranted = true
        // 判断是否所有的权限都已经授予了
        for (grant in grantResults) {
            if (grant != PackageManager.PERMISSION_GRANTED) {
                isAllGranted = false
                break
            }
        }

        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (!isAllGranted) {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
                openAppDetails()
            } else {
                grantedAllPermissions()
            }
        }
    }

    /**
     * WRITE_SETTINGS需要手动才能打开
     * 设置系统写权限
     */
    protected open fun openWriteSettings() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                val intent = Intent(
                    Settings.ACTION_MANAGE_WRITE_SETTINGS,
                    Uri.parse("package:$packageName")
                )
                startActivityForResult(intent, ACTIVITY_REQUEST_SYSTEM_SETTINGS_CODE)
            }
        }
    }


    /**
     * 打开安装包权限访问
     */
    protected open fun openPackageInstalls(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val haveInstallPermission = packageManager.canRequestPackageInstalls()
            if (!haveInstallPermission) {
                val packageURI = Uri.parse("package:$packageName")
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                startActivityForResult(intent, ACTIVITY_REQUEST_INSTALL_PERMISS_CODE)
                false
            } else {
                true
            }
        } else {
            // Android 8.0以下的应用可以直接安装程序
            true
        }
    }


    /**
     * 打开 APP 的详情设置,手动进入设置页面。
     */
    private fun openAppDetails() {
        val builder = AlertDialog.Builder(this)
        builder.setMessage("请到 “应用信息 -> 权限” 中授予！")
        builder.setPositiveButton("去手动授权") { _, _ ->
            val intent = Intent()
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            intent.data = Uri.parse("package:$packageName")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
            startActivityForResult(intent, ACTIVITY_REQUEST_GO_APPINFO_PAGE)
//            startActivity(intent)
        }
        builder.setNegativeButton("取消", null)
        builder.show()
    }

    /**
     * Activity的响应结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            ACTIVITY_REQUEST_GO_APPINFO_PAGE -> {
                checkPermissions()
            }
            ACTIVITY_REQUEST_SYSTEM_SETTINGS_CODE -> {
                checkPermissions()
            }
            ACTIVITY_REQUEST_INSTALL_PERMISS_CODE -> {
                checkPermissions()
            }
        }
    }

    /**
     * 伴身类
     */
    companion object {
        /**
         * 权限请求授权码
         */
        private const val PERMISSION_REQUEST_CODE = 10000

        /**
         * 进入应用信息页面
         */
        private const val ACTIVITY_REQUEST_GO_APPINFO_PAGE = 10010

        /**
         * 安装权限请求码 ACtivity跳转
         */
        private const val ACTIVITY_REQUEST_INSTALL_PERMISS_CODE = 10020

        /**
         * 系统设置权限
         */
        private const val ACTIVITY_REQUEST_SYSTEM_SETTINGS_CODE = 10030
    }
}